package com.miku.blog.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.miku.blog.domain.Tourist;
import com.miku.blog.domain.UserLoginInfo;
import com.miku.blog.domain.pojo.IpAddressesDetail;
import com.miku.blog.domain.pojo.LoginUser;
import com.miku.blog.domain.pojo.ResponseResult;
import com.miku.blog.domain.pojo.SystemConstance;
import com.miku.blog.service.TouristService;
import com.miku.blog.mapper.TouristMapper;
import com.miku.blog.utils.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;


/**
* @author Miku
* @description 针对表【tb_tourist】的数据库操作Service实现
* @createDate 2022-06-18 02:51:38
*/
@Service
public class TouristServiceImpl extends ServiceImpl<TouristMapper, Tourist>
    implements TouristService{


    @Autowired
    private RestTemplate restTemplate;

    @Override
    public Integer addTourist() {

        String nickName = SystemConstance.TOURIST_DEFAULT_NICKNAME;

        IpAddressesDetail ipAddressesDetail = IpAddressesUtils.getIpAddressesDetail(restTemplate);
        UserAgentParseUtils.UserAgentParse agent
                = UserAgentParseUtils.parseUserAgent(null);
        String location = UserUtils.getIpLocation(ipAddressesDetail);

        Tourist tourist = new Tourist();
        tourist.setIpAddress(ipAddressesDetail.getIp())
                .setIpSource(location)
                .setBrowser(agent.getBrowserName())
                .setOs(agent.getSystemName())
                .setNickname(nickName);

        if (!save(tourist)){
            return null;
        }

        return tourist.getId();

    }


    @Override
    public ResponseResult updateTourist(Integer reportId) {


        LoginUser loginUser = SecurityUtils.getLoginUser();
        UserLoginInfo userLoginInfo = loginUser.getUserLoginInfo();
        String nickname = loginUser.getUserInfo().getNickname();
        LambdaUpdateWrapper<Tourist> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(Tourist::getId,reportId)
                .eq(Tourist::getIpAddress,userLoginInfo.getIpAddr())
                .eq(Tourist::getIpSource,userLoginInfo.getIpSource())
                .set(Tourist::getNickname,nickname);
        update(updateWrapper);
        return ResponseResult.ok();
    }
}




